﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace GeoSketch2.Core
{
    /// <summary>
    /// A class to handle inputs outputs with files
    /// </summary>
    public static class FileIO
    {
        #region GeoTagged image parameter file
        /// <summary>
        /// Writes the parameter of a geotaggedimage to a file
        /// </summary>
        public static void WriteGSP(this GeoTaggedImage GeoTaggedImage)
        {
            XmlWriter Xw = GetXmlWriter(Path.GetDirectoryName(GeoTaggedImage.FullFileName) + "\\" + Path.GetFileNameWithoutExtension(GeoTaggedImage.FullFileName) + ".gsp");

            #region Document
            Xw.WriteStartDocument();
            Xw.WriteStartElement(GeoTaggedImage.XML_ImageExtents);

            GeoTaggedImage.ImageExtents.ToFile(Xw);

            Xw.WriteEndElement();
            Xw.WriteEndDocument();
            #endregion

            Xw.Close();
        }

        /// <summary>
        /// Reads the parameter of a geotaggedimage to a file
        /// </summary>
        public static RectangleD ReadGSP(string PictureFilename)
        {
            XmlReader Xr = GetXmlReader(Path.GetDirectoryName(PictureFilename) + "\\" + Path.GetFileNameWithoutExtension(PictureFilename) + ".gsp");

            #region Document
            Xr.ReadToFollowing(typeof(RectangleD).FullName);

            RectangleD dst = new RectangleD(Xr);

            #endregion
            Xr.Close();

            return dst;
        } 
        #endregion

        #region Get common XmlWriter/Reader
        /// <summary>
        /// Gets an XmlWriter from a file, with the default options
        /// </summary>
        public static XmlWriter GetXmlWriter(string Filename)
        {
            XmlWriterSettings Settings = new XmlWriterSettings();
            Settings.ConformanceLevel = ConformanceLevel.Document;
            Settings.Encoding = Encoding.Unicode;
            Settings.Indent = true;
            Settings.IndentChars = "\t";
            Settings.NewLineHandling = NewLineHandling.Entitize;
            return XmlWriter.Create(Filename, Settings);
        }

        /// <summary>
        /// Gets an XmlReader from a file, with the default options
        /// </summary>
        public static XmlReader GetXmlReader(string Filename)
        {
            XmlReaderSettings Setting = new XmlReaderSettings();
            Setting.ConformanceLevel = ConformanceLevel.Document;
            Setting.IgnoreWhitespace = true;
            return XmlReader.Create(Filename, Setting);
        } 
        #endregion

        #region Get common TextWriter/Reader

        public static TextWriter GetTextWriter(string Filename, bool Append)
        {
            TextWriter Tw = new StreamWriter(Filename, Append);
            return Tw;
        }

        #endregion
    }
}
